package manage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LoginManager {

    public static boolean login(String username, String password) {
        try {
            DBManager dbManager = new DBManager();
            ResultSet resultSet = dbManager.queryDB("SELECT * FROM USER_T WHERE USERNAME='" + username + "'");
            resultSet.next();
            String password_DB = resultSet.getString("PASSWORD");
            dbManager.closeConnections();
            if (password_DB.equals(password)) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            return false;
        }
    }

    public static boolean register(String username, String password) {
        DBManager dbManager = new DBManager();
        Connection conn = dbManager.getConnection();
        Statement statement;
        try {
            statement = conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        ResultSet resultSet = dbManager.queryDB("SELECT COUNT(*) FROM USER_T WHERE USERNAME = '" + username +"'");
        try {
            resultSet.next();
            int user_exists = resultSet.getInt(1);
            if (user_exists > 0) {
                return false;
            } else {
                String query = "insert into USER_T values('" + username + "','" + password + "')";
                dbManager.updateDB(query);
                dbManager.closeConnections();
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}